package controller;

import view.GetPlayerMoves;
import view.TableDrawer;
import model.PlayersData;
import model.Table;

public class Gameplay {

	private int movesMade = 0;
	GameSetUp gsu = new GameSetUp();
	PlayersData pd = new PlayersData();
	GetPlayerMoves gpm = new GetPlayerMoves();
	Table gameTable = new Table(GameSetUp.TABLE_SIZE);
	Winner winner = new Winner();
	int whoIsOnMove = -1;

	public void gamePlay() {
		gsu.setUpGame();
		int index = 0;
		while (freeMoves(index)) {
			gpm.whoIsOnTurn(pd.getPlayers()[index].getName());
			int row = gpm.getPlayerRow();
			int col = gpm.getPlayerCol();
			if (avilableMove(row, col)) {
				Table.updateArray(row, col, pd.getPlayers()[index].getMark());
				if (winner.searchForWinner(row, col,
						pd.getPlayers()[index].getMark())) {
					TableDrawer.drawTable(gameTable.getArray());
					gpm.printWinner(pd.getPlayers()[index].getName());
					break;
				} 
				setMovesMade();
				index = getPlayerTurn(index);
			}
		}
	}

	private boolean freeMoves(int index) {
		TableDrawer.drawTable(gameTable.getArray());
		if (GameSetUp.TABLE_SIZE * GameSetUp.TABLE_SIZE <= getMovesMade()) {
			System.out.println("The game is draw!");
			return false;
		}
		return true;
	}

	private boolean avilableMove(int row, int col) {
		if (gameTable.getArray()[row][col] == ' ') {
			return true;
		}
		gpm.printNotAvilableMove();
		return false;
	}

	private void setMovesMade() {
		this.movesMade += 1;
	}

	private int getMovesMade() {
		return movesMade;
	}

	private int getPlayerTurn(int index) {
		index++;
		if (index < GameSetUp.NUMBER_OF_PLAYERS) {
			return index;
		} else {
			return 0;
		}
	}
}